package com.topone.controller;

import com.topone.Utils.KeyUntil;
import com.topone.config.WechatAccessConfig;
import com.topone.dto.TcUserDTO;
import com.topone.reponse.QrcodeResponse;
import com.topone.service.TcUserService;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpQrCodeTicket;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.net.URLEncoder;
import java.util.Map;
import java.util.Objects;

/**
 * Created by Administrator on 2017/11/20,0020.
 */
@CrossOrigin
@Controller
@RequestMapping("/buyer")
@Slf4j
public class WechatController {

    @Autowired
    private WxMpService wxMpService;

    @Autowired
    private TcUserService tcUserService;

    @Autowired
    private WechatAccessConfig wechatAccessConfig;

    @GetMapping("/authorize")
    public String authorize(@RequestParam("returnUrl") String returnUrl){

        //1.配置
        //2.调用方法
        //String url="http://qingzhao.nat300.top/fanZone/buyer/userInfo";
        String url=wechatAccessConfig.getUrl();
        String redirectUrl= wxMpService.oauth2buildAuthorizationUrl(url,WxConsts.OAUTH2_SCOPE_USER_INFO,URLEncoder.encode(returnUrl));
       return "redirect:" +redirectUrl;
    }

    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("code") String code, @RequestParam("state") String returnUrl,
                                 Map<String,Object> map){
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken=new WxMpOAuth2AccessToken();
        WxMpUser wxMpUser=new WxMpUser();
        try {
            wxMpOAuth2AccessToken=wxMpService.oauth2getAccessToken(code);
            wxMpUser=wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken,"zh_CN");
        }catch (Exception e){
            log.error("【微信授权】失败，{}",wxMpUser);
        }

        String openId=wxMpUser.getOpenId();
        TcUserDTO tcUserDTO = tcUserService.findUserInfoByopenid(openId);
        if(!StringUtils.isEmpty(openId)){
            returnUrl=returnUrl+"#openid="+openId;
        }else{
            returnUrl=returnUrl+"#error";
        }
        if(tcUserDTO==null){  //用户第一次关注
            tcUserDTO = new TcUserDTO();
            //设置用户id
            tcUserDTO.setUserId(KeyUntil.getUniqueKey());
            //用户openId

            tcUserDTO.setOpenid(openId);
            //用户昵称
            tcUserDTO.setUserName(wxMpUser.getNickname());
            //用户性别
                tcUserDTO.setGender(wxMpUser.getSex());

            //用户所在省份
            tcUserDTO.setProvince(wxMpUser.getProvince());
            //用户所在城市
            tcUserDTO.setCountry(wxMpUser.getCountry());
            //用户所在国家
            tcUserDTO.setCity(wxMpUser.getCity());
            //用户头像
            tcUserDTO.setHeadUrl(wxMpUser.getHeadImgUrl());

            try {
              tcUserService.insertUserInfo(tcUserDTO);
            }catch (Exception e){
               log.error("【插入用户信息】失败",e);
               e.printStackTrace();
            }
            log.info("【插入用户信息】成功,{}",openId);
        }else{
            tcUserDTO.setOpenid(openId);
            //更新用户昵称
            tcUserDTO.setUserName(wxMpUser.getNickname());
            //更新用户性别
                tcUserDTO.setGender(wxMpUser.getSex());
            //用户所在省份
            tcUserDTO.setProvince(wxMpUser.getProvince());
            //用户所在城市
            tcUserDTO.setCountry(wxMpUser.getCity());
            //用户所在国家
            tcUserDTO.setCity(wxMpUser.getCountry());
            //用户头像
            tcUserDTO.setHeadUrl(wxMpUser.getHeadImgUrl());
            try {
                tcUserService.updateUserInfo(tcUserDTO);
            }catch (Exception e){
                log.error("【更新用户信息】失败",e);
                map.put("error","更新用户信息失败");
               e.printStackTrace();
            }
            log.info("【更新用户信息】成功,{}",openId);
        }

          return "redirect:" +returnUrl;
    }

    @RequestMapping(value = "/{couponCode}/qrcode",
            method = RequestMethod.GET,
            produces = MediaType.APPLICATION_JSON_UTF8_VALUE)
    @ResponseBody
    public QrcodeResponse qrcodeResponse(@PathVariable String couponCode) throws WxErrorException {
        log.info("QRCode: "+couponCode);
        String groupIdStr= "http://www.baidu.com";
        WxMpQrCodeTicket ticket = wxMpService.getQrcodeService().qrCodeCreateLastTicket(groupIdStr);
        return new QrcodeResponse(wxMpService.getQrcodeService().qrCodePictureUrl(ticket.getTicket()));
    }


    @GetMapping("/authorize/base")
    public String authorizeBase(@RequestParam("returnUrl") String returnUrl){

        //1.配置
        //2.调用方法
        //String url="http://qingzhao.nat300.top/fanZone/buyer/userInfo";
        String url=wechatAccessConfig.getBaseUrl();
        String redirectUrl= wxMpService.oauth2buildAuthorizationUrl(url,WxConsts.OAUTH2_SCOPE_BASE,URLEncoder.encode(returnUrl));
        return "redirect:" +redirectUrl;
    }

    @GetMapping("/baseInfo")
    public String baseInfo(@RequestParam("code") String code, @RequestParam("state") String returnUrl,
                           Map<String,Object> map) {
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken = new WxMpOAuth2AccessToken();
        WxMpUser wxMpUser = new WxMpUser();
        try {
            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
            wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
        } catch (Exception e) {
            log.error("【微信授权】失败，{}", wxMpUser);
        }

        String openId = wxMpUser.getOpenId();
        TcUserDTO tcUserDTO = tcUserService.findUserInfoByopenid(openId);
        if(Objects.isNull(tcUserDTO)){
            tcUserDTO.setOpenid(openId);
        }
        if(!StringUtils.isEmpty(openId)){
            returnUrl=returnUrl+"#openid="+openId;
        }else{
            returnUrl=returnUrl+"#error";
        }
        return returnUrl;
    }
}
